package com.sita.bike.ui.fragments;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.sita.bike.R;
import com.sita.bike.event.DrawResourceEvent;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.RtResourceNearRequest;
import com.sita.bike.rest.model.RangeListResponse;
import com.sita.bike.rest.model.Resource2;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.task.ResoureListLoadTask;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.LogUtils;
import com.sita.bike.utils.RetrofitUtils;
import com.sita.tboard.ui.activity.RtTrendDetailActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Class MapFriendFragment contains location markers for me and contacts
 *
 * @author markman on 16/02/15.
 */
public class MapFriendFragment extends BasicMapFragment implements AMap.OnMarkerClickListener {

    private static final String TAG = MapFriendFragment.class.getSimpleName();
    private static final int STATUS_NORMAL = 0;
    private static final String SMOOTH = "smooth";
    private static final String SLOW = "slow";
    private static final String CONGESTION = "congestion";
    private int mStatus = STATUS_NORMAL;
    private Map<String, Marker> mMessageMarkers;
    private Map<String, String> mMarkerIdMessageMap;

    private List<Resource2> mResourceList;
    private List<Resource2> mResourceListNew;
    protected boolean mHasGetResource = false;

    public MapFriendFragment() {
        mMessageMarkers = new HashMap<String, Marker>();
        mMarkerIdMessageMap = new HashMap<String, String>();
    }

    public static MapFriendFragment newInstance() {
        MapFriendFragment fragment = new MapFriendFragment();
        return fragment;
    }

    protected void removeAllMarker() {
        List<Marker> allMarks = aMap.getMapScreenMarkers();
        for (Marker m : allMarks
                ) {
            if (!m.getId().equals(myMarker.getId())) {
                m.remove();
            }
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        aMap.setOnMarkerClickListener(this);
        fetchResource();
        super.onViewCreated(view, savedInstanceState);
    }

    protected void clearMap() {
        aMap.clear();
        removeAllMarker();
        if (mResourceList != null) {
            mResourceList.clear();
        }

        if (mResourceListNew != null) {
            mResourceListNew.clear();
        }

        if (mMarkerIdMessageMap != null) {
            mMarkerIdMessageMap.clear();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);

    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(DrawResourceEvent event) {
        Toast.makeText(getActivity(), event.accountId, Toast.LENGTH_SHORT);

        drawRoadMatesMarker(event.res, event.bmp);
//        moveBound();

    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        if (mHasGetResource == false && location != null && location.getLatitude() > 0) {
            fetchResource();
        }
        super.onLocationChanged(location);
    }

    protected boolean canDrawRoadMatesMarker() {
        return true;
    }

    private void drawRoadMatesMarker(Resource2 res, Bitmap bmp) {

        if (!canDrawRoadMatesMarker()) {
            return;
        }


        // Check if the resource has been added into map
        if (mMarkerIdMessageMap.containsValue(res.mResourceId)) {
            return;
        }
        //mMarkerIdMessageMap;
        LatLng latLng;
        Marker marker;
        Bitmap bitmap = null;
        BitmapDescriptor icon;
        if (res.mTrafficType.equalsIgnoreCase(SMOOTH)) {
            bitmap = BitmapUtils.composeBitmap(R.drawable.location_green, bmp, 100, 75,0.9f);
        } else if (res.mTrafficType.equalsIgnoreCase(SLOW)) {
            bitmap = BitmapUtils.composeBitmap(R.drawable.location_yellow, bmp, 100, 75,0.9f);
        } else if (res.mTrafficType.equalsIgnoreCase(CONGESTION)) {
            bitmap = BitmapUtils.composeBitmap(R.drawable.location_red, bmp, 100, 75,0.9f);
        }
        icon = BitmapDescriptorFactory.fromBitmap(bitmap);
        latLng = new LatLng(Double.valueOf(res.mLocation.latitude),
                Double.valueOf(res.mLocation.longitude));
        Log.d("Markers", "LatLng = " + latLng.toString());
        marker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon).position(latLng));
        mMessageMarkers.put(String.valueOf(mMessageMarkers.size()), marker);

        mMarkerIdMessageMap.put(marker.getId(), res.mResourceId);


    }

    private void moveBound() {
        if (!mMessageMarkers.values().isEmpty()) {
            LatLngBounds bounds = aMap.getProjection().getVisibleRegion().latLngBounds;
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            if (myMarker != null) {
                builder.include(myMarker.getPosition());
            }
            boolean changeBounds = false;
            if (!bounds.contains(myMarker.getPosition())) {
                changeBounds = true;
            }
            for (Marker marker : mMessageMarkers.values()) {
                if (!bounds.contains(marker.getPosition())) {
                    builder.include(marker.getPosition());
                    changeBounds = true;
                }
            }
            if (changeBounds) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0));
                float zoomLevel = aMap.getCameraPosition().zoom - 1;
                aMap.moveCamera(CameraUpdateFactory.zoomTo(zoomLevel));
            }
        } else {
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(myMarker.getPosition()).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(aMap.getCameraPosition().bearing).tilt(aMap.getCameraPosition().tilt).build();
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.getId().equals(myMarker.getId())) {
            return true;
        } else {
            // show pop message activity
            String resourceId = mMarkerIdMessageMap.get(marker.getId());
            String usernam = marker.getTitle();
            Intent intent = new Intent(getActivity(), RtTrendDetailActivity.class);
            intent.putExtra(RtTrendDetailActivity.BIND_RESOURCE_ID, resourceId);
//            intent.putExtra("header", BitmapUtils.bitmapToBytes(marker.getIcons().get(0).getBitmap()));
//            intent.putExtra("username", usernam);
            startActivity(intent);
            return false;
        }

    }


    // Get the resource list
    protected void fetchResource() {
        AMapLocation aloc;
        aloc = GlobalContext.getLocationClient().getLastKnownLocation();

        if (aloc == null) {
            LogUtils.d(TAG, "fetch resource failed, no location");
            return;
        }

        RtResourceNearRequest rlp = new RtResourceNearRequest();

        rlp.mAccountId = AccountUtils.getAccountID();

        Location location = new Location();
        location.latitude = String.valueOf(aloc.getLatitude());
        location.longitude = String.valueOf(aloc.getLongitude());
        location.province = aloc.getProvince();
        location.city = aloc.getCity();

        rlp.mLocation = location;
        rlp.mPageNumber = "0";
        rlp.mPageSize = "20";
        rlp.mEndDate = System.currentTimeMillis();

        RestClient.getRestNormalService().rtResourceNear(rlp, new Callback<RangeListResponse>() {
            @Override
            public void success(RangeListResponse rangeListResponse, Response response) {
                if (response.getStatus() == 200 &&
                        rangeListResponse.mErrorCode.equals("0") &&
                        rangeListResponse.mDatas.size() > 0) {
                    if (mResourceList == null) {
                        mResourceList = new ArrayList<Resource2>();
                    }

                    if (mResourceListNew == null) {
                        mResourceListNew = new ArrayList<Resource2>();
                    }

                    mResourceListNew = rangeListResponse.mDatas;
                    mResourceListNew.removeAll(mResourceList);
                    mResourceList.addAll(mResourceListNew);

                    Log.d(TAG, "load ok");

                    if (mResourceListNew.size() > 0) {
                        fetchHeaderImages();
                    }
                    mHasGetResource = true; // if first time get resource ok, then no need to get it from location changed
                }
                Log.d(TAG, response.getReason());
            }

            @Override
            public void failure(RetrofitError error) {
                RetrofitUtils.displayError(getActivity(), error);
                LogUtils.e(TAG, "fetch resource error");
            }
        });
    }

    private void fetchHeaderImages() {
        new ResoureListLoadTask(mResourceListNew).execute();
    }

    private Bitmap mergeBitmap(Bitmap firstBitmap, Bitmap secondBitmap) {
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap.getHeight(),
                firstBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(firstBitmap, new Matrix(), null);
        canvas.drawBitmap(secondBitmap, 0, 0, null);
        return bitmap;
    }

    public void first(ImageView v, Bitmap bmp) {
        Bitmap bitmap1 = bmp;
        Bitmap bitmap2 = ((BitmapDrawable) getResources().getDrawable(
                R.drawable.location_red)).getBitmap();

        Bitmap newBitmap = null;

        newBitmap = Bitmap.createBitmap(bitmap1);
        Canvas canvas = new Canvas(newBitmap);
        Paint paint = new Paint();

        int w = bitmap1.getWidth();
        int h = bitmap1.getHeight();

        int w_2 = bitmap2.getWidth();
        int h_2 = bitmap2.getHeight();

        paint.setColor(Color.GRAY);
        paint.setAlpha(125);
        canvas.drawRect(0, 0, bitmap1.getWidth(), bitmap1.getHeight(), paint);

        paint = new Paint();
        canvas.drawBitmap(bitmap2, Math.abs(w - w_2) / 2,
                Math.abs(h - h_2) / 2, paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        // 存储新合成的图片
        canvas.restore();

        v.setImageBitmap(newBitmap);
    }

}
